package com.gesonet.oauth2.api;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gesonet.oauth2.util.HttpKit;
import com.gesonet.oauth2.util.HttpKitExt;
import com.gesonet.oauth2.util.PropertiesUtils;


/**
 * @ClassName: Oauth 
 * @Description: TODO
 * @author QinXiaoXiang
 * @date 2016年8月9日 下午1:49:29 
 */
public abstract class Oauth {
	
	protected final Logger LOGGER = LoggerFactory.getLogger(Oauth.class);
	protected String appId;
	private String appSecret;
	private String redirectUri;

	public Oauth() {
		String name = getSelf().getClass().getSimpleName();
		appId = PropertiesUtils.getString(name + ".openid");
		appSecret = PropertiesUtils.getString(name + ".openkey");
		redirectUri = PropertiesUtils.getString(name + ".redirect");
	}
	
	public Oauth(String redirectUri){
		String name = getSelf().getClass().getSimpleName();
		appId = PropertiesUtils.getString(name + ".openid");
		appSecret = PropertiesUtils.getString(name + ".openkey");
		this.redirectUri = redirectUri;
	}
	
	public Oauth(String appId,String appSecret,String redirectUri){
		this.appId = appId;
		this.appSecret = appSecret;
		this.redirectUri = redirectUri;
	}

	public abstract Oauth getSelf();

	/**
	 * 构造授权的Url
	 * @param authorize url
	 * @param state OAuth2.0标准协议建议，利用state参数来防止CSRF攻击。可存储于session或其他cache中
	 * @return String 构造完成的url字符串
	 */
	protected String getAuthorizeUrl(String authorize, String state) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("response_type", "code");
		params.put("scope", "snsapi_login");
		params.put("client_id", getAppId());
		params.put("redirect_uri", getRedirectUri());
		if (StringUtils.isNotBlank(state)) {
			params.put("state", state);
		}
		return HttpKitExt.initParams(authorize, params);
	}

	protected String doPost(String url, Map<String, String> params) {
		return HttpKit.post(url, HttpKitExt.map2Url(params));
	}

	protected String doGet(String url, Map<String, String> params) {
		return HttpKit.get(url, params);
	}

	protected String doGetWithHeaders(String url, Map<String, String> headers) {
		return HttpKit.get(url, null, headers);
	}

	public void setAppId(String appId){
		this.appId = appId;
	}
	
	public String getAppId() {
		return appId;
	}

	public void setAppSecret(String appSecret){
		this.appSecret = appSecret;
	}
	
	public String getAppSecret() {
		return appSecret;
	}

	public void setRedirectUri(String redirectUri){
		this.redirectUri = redirectUri;
	}
	
	public String getRedirectUri() {
		return redirectUri;
	}
}
